package com.service.impl;

import com.alibaba.fastjson.JSON;
import com.dao.DepartmentDao;
import com.pojo.Department;
import com.pojo.RoomType;
import com.service.DepartmentService;
import com.util.JedisPoolUtils;
import com.util.RedisKey;
import com.vo.DepartmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.Date;
import java.util.List;

/**
 * @author mornd
 * @date 2020/11/16 - 10:25
 */
@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentDao departmentDao;

    /**
     * 根据条件查询部门
     * @param departmentVo
     * @return
     */
    public List<Department> findDepartment(DepartmentVo departmentVo) {
        return departmentDao.findDepartment(departmentVo);
    }

    /**
     * 添加部门
     * @param department
     * @return
     */
    public int addDepartment(Department department) {
        department.setCreateDate(new Date());
        int count = departmentDao.addDepartment(department);
        if(count > 0){
            JedisPoolUtils.getJedis().del(RedisKey.DEPT_LIST);
            findDeptByRedis();
        }
        return count;
    }

    /**
     * 修改部门
     * @param department
     * @return
     */
    public int updateDepartment(Department department) {
        int count = departmentDao.updateDepartment(department);
        if(count > 0){
            JedisPoolUtils.getJedis().del(RedisKey.DEPT_LIST);
            findDeptByRedis();
        }
        return count;
    }

    /**
     * 删除部门
     * @param deptId
     * @return
     */
    public int deleteDepartment(Integer deptId) {
        int count = departmentDao.deleteDepartment(deptId);
        if(count > 0){
            JedisPoolUtils.getJedis().del(RedisKey.DEPT_LIST);
            findDeptByRedis();
        }
        return count;
    }

    //通过redis缓存查询下拉列表部门集合
    public String findDeptByRedis() {
        //创建jedis对象
        Jedis jedis = JedisPoolUtils.getJedis();
        //拿取房型集合的键
        String deptList = jedis.get(RedisKey.DEPT_LIST);
        //判断是否为空
        if(StringUtils.isEmpty(deptList)){
            //从数据库中查询数据
            List<Department> departments = findDepartment(null);
            //将数据添加至缓存中
            deptList = jedis.set(RedisKey.DEPT_LIST, JSON.toJSONString(departments));
        }
        return deptList;
    }
}
